package cn.josh.action;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.josh.bean.Ec_shopcar;
import cn.josh.service.Ec_shopcarService;
import cn.josh.servicelmpl.Ec_shopcarServiceImpl;


@WebServlet("/ArticleCarReadServlet")
public class ArticleCarReadServlet extends HttpServlet 
{
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		//得到用户id
		HttpSession session = request.getSession();
		String userId = (String)session.getAttribute("userId");
		System.out.println("ArticleCarDeleteServlet---userId:" + userId);
		
		//取得数据库服务
		Ec_shopcarService shopList = new Ec_shopcarServiceImpl();
		List<Ec_shopcar> list = shopList.findCarList(userId);
		
		//计算购物车总价格与商品数量
		double allPrice = 0;
		int allCount = 0;
		if(list != null)
		{
			for(Ec_shopcar car : list)
			{
				if(car.getPrice() == null)
				{
					car.setPrice("0");
				}
				if(car.getBuyNum() == null)
				{
					car.setBuyNum("0");
				}
				if(car.getDiscount() == null)
				{
					car.setDiscount("0");
				}
				
				allPrice += Double.parseDouble(car.getPrice()) * Double.parseDouble(car.getDiscount()) * Double.parseDouble(car.getBuyNum());
				//将数据转换成两位小数
				BigDecimal b = new BigDecimal(allPrice);  
				allPrice = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
				allCount++;
			}
				
		}
		
		System.out.println(allPrice);
		//将搜索到的集合存放在request
		request.setAttribute("carList", list);
		request.setAttribute("allPrice", allPrice);
		request.setAttribute("allCount", allCount);
		
		
		request.getRequestDispatcher("jsp/sp_car.jsp").forward(request, response); 
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		doGet(request, response);
	}

}
